package com.jlkf.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jlkf.common.Constant;
import com.jlkf.common.ExportExcel;
import com.jlkf.common.rong.models.TokenResult;
import com.jlkf.common.rong.util.RongCloud;
import com.jlkf.dao.*;
import com.jlkf.pojo.*;
import com.jlkf.service.UserService;
import com.jlkf.service.util.FireBaseUtil;
import com.jlkf.temp.CommonUtils;
import com.jlkf.temp.Page;
import com.jlkf.view.CompaniesExport;
import com.jlkf.view.OA.DriverListExport;
import com.jlkf.view.OA.PassengersListExport;
import com.platform.server.response.response.pojo.ReturnData;
import com.platform.server.util.DateUtil;
import com.platform.server.util.HttpRequestUtil;
import com.platform.server.util.MD5Util;
import com.platform.server.util.RandomUtil;
import com.platform.server.util.RegexUtil;
import com.platform.server.util.StringTools;
import com.platform.server.util.UUIDUtil;

import Decoder.BASE64Decoder;
import net.sf.json.JSONObject;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Service
public class UserServiceImpl implements UserService{

	@Autowired
	private UserMapper userMapper;
	@Autowired
	private CityRecordMapper cityRecordMapper;
	@Autowired
    private UserBrankMapper userBrankMapper;
	@Autowired
    private DriverAccessoryMapper driverAccessoryMapper;
	@Autowired
	private ConfigManagerMapper configManagerMapper;
	@Autowired
	private UserCouponMapper userCouponMapper;
	@Autowired
	private GisRecordMapper gisRecordMapper;
	@Autowired
	private AuthcodeMapper authCodeMapper;
	@Autowired
	private JedisPool jedisPool;
	@Override
	public Object getUserList(String startTime,String endTime,String telephone,Integer sex,Integer isOnline,Integer pageNo,Integer pageSize,Integer isDeleted
			,String order,String sortname) {
	     Map<String,Object> map = new HashMap<>();
	     if(!StringTools.isEmpty(startTime)&&!StringTools.isEmpty(endTime)){
	    	String[] startTime1= startTime.split("/");
	    	String[] endTime1= endTime.split("/");
	    	map.put("startTime", startTime1[2]+"-"+startTime1[1]+"-"+startTime1[0]);
	    	map.put("endTime", endTime1[2]+"-"+endTime1[1]+"-"+endTime1[0]);
	    }
	    if(!StringTools.isEmpty(telephone)){
	    	if(telephone.length()>8){
	    		telephone=telephone.substring(telephone.length()-8);
	    	}
	    	map.put("telephone", telephone);
	    }
	    if(sex!=null){
	    	map.put("sex", sex);
	    }
	    if(isDeleted!=null){
	    	map.put("isDeleted", isDeleted);
	    }
	    if(isOnline!=null){
	    	map.put("isOnline", isOnline);
	    }
	    if(RegexUtil.isNull(pageNo)){
	    	pageNo=1;
	    }
	    if(RegexUtil.isNull(pageSize)){
	    	pageSize=10;
	    }
	    if(!StringTools.isEmpty(sortname)){
	    	if(sortname.equals("login_time")){
	    		map.put("sortname", "login_time");
	    	}else{
	    		map.put("sortname", "create_time");
	    	}
	    	 if(!StringTools.isEmpty(order)){
	 	    	map.put("order", order);
	 	    }
	    }
	    try {
	    	PageHelper.startPage(pageNo,pageSize);
			List<User> list = userMapper.getUserList(map);
			PageInfo<User> info = new PageInfo(list);
			Integer totalPage= info.getPages();
			Integer totalRecord = (int) info.getTotal();
			return new ReturnData(list,totalPage,totalRecord,200,"User list ");
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500,"Wow, that's wrong");
		}
	}

	@Override
	public Object getCityList(Integer pageNo, Integer pageSize) {
		 Map<String,Object> map = new HashMap<>();
		    if(RegexUtil.isNull(pageNo)){
		    	pageNo=1;
		    }
		    if(RegexUtil.isNull(pageSize)){
		    	pageSize=10;
		    }
		try {
			PageHelper.startPage(pageNo, pageSize);
			List<CityRecord> list = cityRecordMapper.getList(map);
			PageInfo<User> info = new PageInfo(list);
			Integer totalPage= info.getPages();
			Integer totalRecord = (int) info.getTotal();
			return new ReturnData(list,totalPage,totalRecord,200,"city list ");
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500,"Wow, that's wrong");
		}
	}

	//用户详情
	public void getUserInfo(User user, Map<String, Object> map) {
		User temp = userMapper.selectByPrimaryKey(user.getId());
		map.put("user",temp);
		List<Map> invitors = userMapper.getInvitors(temp);
		map.put("invitors",invitors);
	}

	//更新用户
	public Object updateUser(User user) {
		if(user.getIsDeleted()==1){//禁用
			User u=userMapper.selectByPrimaryKey(user.getId());//通知前端 该司机被封  不能使用
			FireBaseUtil.sendMessageAlert(u.getUseEquipment(), "{\"type\":4,\"userId\":"+user.getId()+"}");
//			SendPushNotification.sendMessageSilentDriver(u.getUseEquipment(), "{\"type\":4,\"userId\":"+user.getId()+"}", u.getAuroraAlias());
//			AuroraPush.pushTargetForDriver(user.getId().toString(), "{\"type\":4,\"userId\":"+user.getId()+"}", u.getAuroraAlias());
		}
		return userMapper.updateByPrimaryKeySelective(user);
	}

    //司机列表
    public ReturnData getDrivers(String createTimes,String loginTimes,User user, Page page) {
	    ReturnData result = new ReturnData(null);
	    if(user.getSortname()!=null&&"".equals(user.getSortname())){
	    	user.setSortname(null);
	    }
	    if(!StringTools.isEmpty(user.getSortname())){
	    	if(user.getSortname().equals("remark")){
	    		user.setSortname("remark");
	    	}else{
	    		user.setSortname("create_time");
	    	}
	    	
	    }else{
	    	 if(!StringTools.isEmpty(user.getOrder())){
	    		 user.setOrder(null);
	 	    }
	    }
	    if(!StringTools.isEmpty(createTimes)&&!StringTools.isEmpty(loginTimes)){
	    	String[] startTime1= createTimes.split("/");
	    	String[] endTime1= loginTimes.split("/");
	    	user.setLoginTime(DateUtil.parseDate(endTime1[2]+"-"+endTime1[1]+"-"+endTime1[0]));
	    	user.setCreateTime(DateUtil.parseDate(startTime1[2]+"-"+startTime1[1]+"-"+startTime1[0]));
	    }
	    if(!StringTools.isEmpty(user.getTelephone())){
	    	String telephone=user.getTelephone();
	    	if(telephone.length()>8){
	    		user.setTelephone(telephone.substring(telephone.length()-8));;
	    	}
	    }
	    PageHelper.startPage(page.getPageNo(),page.getPageSize());
	    List<Map> list = userMapper.getDrivers(user);
	    PageInfo<Map> info = new PageInfo<>(list);
	    result.setPageNo(info.getPageNum());
	    result.setTotalPage(info.getPages());
	    result.setTotalRecord((int) info.getTotal());
	    result.setData(list);
        return result;
    }

    //司机详情
    public void getDriverInfo(User user, Map<String, Object> map) {
        User temp = userMapper.selectByPrimaryKey(user.getId());
        map.put("user",temp);
        //银行卡
        List<UserBrank> cards = userBrankMapper.getUserCards(temp.getId());
        map.put("cards",cards);
        //车
        List<DriverAccessory> cars = driverAccessoryMapper.getUserCars(temp.getId());
        DriverAccessory car = null;
        if(cars != null && cars.size()>0){
            //默认车辆
            for(DriverAccessory cc:cars){
                if(cc.getIsDefault()==1){
                    car = cc;
                }
            }
            //没有就取第一辆
            if(car == null){
                car = cars.get(0);
            }
            if(car.getPicture()!=null){
                car.setPics(CommonUtils.removeStartAndEndNode(car.getPicture()).split(","));
            }
        }
        map.put("car",car);
    }

    //查看设置
    public Object cancelOrderConf() {
		return configManagerMapper.selectByPrimaryKey(1);
    }
	//更新设置
	public Object orderConf(ConfigManager conf) {
		
		Jedis jedis = null;
		if(jedis == null){
			jedis =jedisPool.getResource();
		}
		try {
			int n=configManagerMapper.updateByPrimaryKeySelective(conf);
			if(n==0){
				return 0;
			}
			ConfigManager cm = configManagerMapper.selectByPrimaryKey(1);
			JSONObject jo = JSONObject.fromObject(cm);
			jedis.set("configManager", jo.toString());
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}finally {
			if(jedis != null){
				jedis.close();
			}
		}
		return 1;
	}

	//企业
	@Override
	public Object getEnterpriseList( String company, Integer pageNo, Integer pageSize,String userAccount) {
		  Map<String,Object> map = new HashMap<>();
		    if(!StringTools.isEmpty(company)){
		    	map.put("company", company);
		    }
		    if(!StringTools.isEmpty(userAccount)){
		    	map.put("userAccount", userAccount);
		    }
		    if(RegexUtil.isNull(pageNo)){
		    	pageNo=1;
		    }
		    if(RegexUtil.isNull(pageSize)){
		    	pageSize=10;
		    }
		    try {
		    	PageHelper.startPage(pageNo,pageSize);
				List<User> list = userMapper.getEnterpriseList(map);
				for(User u:list){
					UserBrank	userBrank =userBrankMapper.getEnterpriseBrank(u.getId());
					u.setUb(userBrank);
				}
				PageInfo<User> info = new PageInfo(list);
				Integer totalPage= info.getPages();
				Integer totalRecord = (int) info.getTotal();
				return new ReturnData(list,totalPage,totalRecord,200,"User list ");
			} catch (Exception e) {
				e.printStackTrace();
				return new ReturnData(500,"Wow, that's wrong");
			}
	}

	@Override
	public Object addEnterprise(String json) {
		User u = StringTools.json2Obj(json, User.class);
		if(u==null){
			return new ReturnData(201,"参数列表为空");
		}
		Map<String,Object> map = new HashMap<>();
		map.put("telephone", u.getTelephone());
		map.put("identity", 4);
		try {
			if(u.getId()!=null){
				 userBrankMapper.updateByPrimaryKeySelective(u.getUb()); 
				int nu=userMapper.updateByPrimaryKeySelective(u);
				if(nu==0){
					return new ReturnData(208,"Save Fail");
				}
			}else{
				 List<User> list=userMapper.getLogin(map);
				 if(list.size()>0){
					 return new ReturnData(209,"This number is already registered. Please enter a different number.");
				 }
				 if(!RegexUtil.isEmail(u.getEmail())){
					 return new ReturnData(208,"Incorrect email format.");
				 }
				 String userNo=getUserNo();
				 u.setUserAccount(userNo);
				 u.setCreateTime(new Date());
				int nu=userMapper.insertSelective(u);
				if(nu==0){
					return new ReturnData(208,"Save Fail");
				}	
				 List<User> lists=userMapper.getNameAndTel(map);
				 if(lists.size()>0){
					 UserBrank ub = u.getUb();
					 ub.setuId(lists.get(0).getId());
					 ub.setCreateTime(new Date());
					 userBrankMapper.insertSelective(ub);//保存卡的信息
				 }
			}
			return new ReturnData(200,"保存成功");
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500,"Wow, that's wrong");
		}
	}
	// 获取订单
			private String getUserNo() {
				String str = userMapper.selectMaxUserNo();
				if (str == null) {
					str = "00000" + 1;
				} else {
					Integer no = Integer.parseInt(str);
					if (no < 9) {
						str = "00000" + (no + 1);
					} else if (no >= 9 && no < 99) {
						str = "0000" + (no + 1);
					} else if (no >= 99 && no < 999) {
						str = "000" + (no + 1);
					}else if(no >= 999 && no < 9999){
						str = "00" + (no + 1);
					}else if(no >= 9999 && no < 99999){
						str = "0" + (no + 1);
					} else {
						str = "" + (no + 1);
					}
				}
				String no = "E" + str;
				return no;
			}
	@Override
	public Object deleteEnterprise(String ids) {
		String [] idList = ids.split(",");
		boolean flag=true;
		try {
		for(String idL:idList){
			Long id = Long.parseLong(idL);
			UserBrank ub=userBrankMapper.getEnterpriseBrank(id);
			userBrankMapper.deleteByPrimaryKey(ub.getUbId());
			int n=	userMapper.deleteByPrimaryKey(id);
			if(n==0){
				flag=false;break;
			}
		}
			if(flag){
				return new ReturnData(200,"删除成功");
			}
			TransactionAspectSupport.currentTransactionStatus().isRollbackOnly();
		    return new ReturnData(201,"删除失败");
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500,"Wow, that's wrong");
		}
	}

	//发劵记录
	@Override
	public Object userEnterpriseCoupon( Long qyId,Integer pageNo,Integer pageSize,String startTime,String endTime,String couponName,String couponNo,String couponCode,String giftedPeopleName) {
		Map<String,Object> map = new HashMap<>();
		map.put("enterpriseId", qyId);
		if(!StringTools.isEmpty(startTime)&&!StringTools.isEmpty(endTime)){
			 String[] startTime1= startTime.split("/");
		    	String[] endTime1= endTime.split("/");
		    	map.put("startTime", startTime1[2]+"-"+startTime1[1]+"-"+startTime1[0]);
		    	map.put("endTime", endTime1[2]+"-"+endTime1[1]+"-"+endTime1[0]);
		}
		if(!StringTools.isEmpty(couponName)){
			map.put("couponName", couponName);
		}
		if(!StringTools.isEmpty(couponNo)){
			map.put("couponNo", couponNo);
		}
		if(!StringTools.isEmpty(couponCode)){
			map.put("couponCode", couponCode);
		}
		if(!StringTools.isEmpty(giftedPeopleName)){
			map.put("giftedPeopleName", giftedPeopleName);
		}
		if(RegexUtil.isNull(pageNo)){
			pageNo=0;	
		}
		if(RegexUtil.isNull(pageSize)){
			pageSize=15;
		}
		try {
             PageHelper.startPage(pageNo, pageSize);
			 List<UserCoupon> list=userCouponMapper.getOAEnterprise(map);
			 PageInfo<UserCoupon> info = new PageInfo<>(list);
			 return new ReturnData(list,(int)info.getPages(),(int)info.getTotal(),200,"list");
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500,"Wow, that's wrong");
		}
	}

	@Override
	public void exportEnterprise(String company, String userAccount, HttpServletResponse response,
			HttpServletRequest request) {
		Map<String,Object> map = new HashMap<>();
		 if(!StringTools.isEmpty(company)){
		    	map.put("company", company);
		    }
		    if(!StringTools.isEmpty(userAccount)){
		    	map.put("userAccount", userAccount);
		    }
		try {
			map.put("starRemarkType", 2);//类别 1司机评价 2app用户评价
			List<User> list = userMapper.getEnterpriseList(map);
			List<Object> list1 = new ArrayList<>();
			 for(User u:list){
				 CompaniesExport ce = new CompaniesExport();
				 ce.setAvailableMoney(u.getAvailableMoney()+"");
				 ce.setName(u.getFirstName());
				 ce.setBusinessLicense(u.getBusinessLicense());
				 ce.setEmail(u.getEmail());
				 ce.setCompany(u.getCompany());
				 ce.setPassword(u.getPassword());
				 ce.setUserAccount(u.getUserAccount());
				 ce.setTelephone(u.getTelephone());
				 list1.add(ce);
			 }
			 String[] Title = {"Business Name","ABN/ CAN", "Business representative", "Business representative contact number", "Business email address", "Business Account ID", "Business Account Password", "Available Balance (AUD)"};
		    ExportExcel.exportExcel("Business Account list.xls", Title, list1, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

	//导出
	@Override
	public void exportUserList(String startTime, String endTime, String telephone, Integer sex, Integer isOnline,
			Integer pageNo, Integer pageSize, Integer isDeleted, String order, String sortname,HttpServletResponse response) {
 Map<String,Object> map = new HashMap<>();
	     
	     if(!StringTools.isEmpty(startTime)&&!StringTools.isEmpty(endTime)){
	    	 String[] startTime1= startTime.split("/");
		    	String[] endTime1= endTime.split("/");
		    	map.put("startTime", startTime1[2]+"-"+startTime1[1]+"-"+startTime1[0]);
		    	map.put("endTime", endTime1[2]+"-"+endTime1[1]+"-"+endTime1[0]);
	    }
	    if(!StringTools.isEmpty(telephone)){
	    	telephone=telephone.substring(telephone.length()-8);
	    	map.put("telephone", telephone);
	    }
	    if(sex!=null){
	    	map.put("sex", sex);
	    }
	    if(isDeleted!=null){
	    	map.put("isDeleted", isDeleted);
	    }
	    if(isOnline!=null){
	    	map.put("isOnline", isOnline);
	    }
	    if(!StringTools.isEmpty(sortname)){
	    	if(sortname.equals("login_time")){
	    		map.put("sortname", "login_time");
	    	}else{
	    		map.put("sortname", "create_time");
	    	}
	    	 if(!StringTools.isEmpty(order)){
	 	    	map.put("order", order);
	 	    }
	    }
	    try {
			List<User> list = userMapper.getUserList(map);
			List<Object> list1 = new ArrayList<>();
			 for(User u:list){
				 PassengersListExport ple = new PassengersListExport();
				 ple.setAddress(u.getAddress());
				 ple.setConsumetotal(u.getConsumetotal());
				 ple.setCreateTime(com.platform.server.util.DateUtil.format(u.getCreateTime(), "yyyy-MM-dd"));
				 ple.setEmail(u.getEmail());
				 ple.setInvitenum(u.getInvitenum());
				 ple.setIsDeleted(u.getIsDeleted()!=null&&u.getIsDeleted()==1?"启用":"禁用");
				 ple.setIsOnline(u.getIsOnline()!=null&&u.getIsOnline()==1?"在线":"离线");
				 ple.setLoginTime(com.platform.server.util.DateUtil.format(u.getLoginTime(), "yyyy-MM-dd"));
				 ple.setMileage(u.getMileage());
				 ple.setName(u.getFirstName());
				 ple.setPostcode(u.getPostcode());
				 String sexs = "male";
				 if(u.getSex()!=null&&u.getSex()==1){
					 sexs = "female";
				 }else if(u.getSex()!=null&&u.getSex()==2){
					 sexs = "other";
				 }
				 ple.setSex(sexs);
				 ple.setTelephone(u.getTelephone());
				 list1.add(ple);
			 }
			 String[] Title = {"Rider Name","Rider Number", "Rider Gender", "Rider email address", "Rider addresses", "Rider post code", "Rider Millage", "Rider total spending","Rider invitation rewards","online/ offline","Registration time","Last login","Status"};
		    ExportExcel.exportExcel("Rider’s list.xls", Title, list1, response);
			
	    }catch (Exception e) {
				// TODO: handle exception
			}
		
	}

	@Override
	public Object getOnLineNum() {
		try {
			String onl=userMapper.getOnLineNum();
			return new ReturnData(onl,200,"success");
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500,"Wow, that's wrong");
		}
	}

	
	@Override
	public ReturnData addDrivers(String json,HttpServletRequest request) {
		User u=StringTools.json2Obj(json, User.class);
		if(u==null){
			return new ReturnData(201,"The parameter list cannot be empty.");
		}
		if(StringTools.isEmpty(u.getTelephone())){
			return new ReturnData(203,"The phone number cannot be empty.");
		}else if(StringTools.isEmpty(u.getEmail())){
			return new ReturnData(204,"Mailbox cannot be empty.");
		}else if(!StringTools.isEmpty(u.getEmail())&&!RegexUtil.isEmail(u.getEmail())){
			return new ReturnData(205,"Mailbox format cannot be empty.");
		}
		Map<String,Object> map = new HashMap<>();
		String telephone=u.getTelephone();
		 telephone=telephone.substring(telephone.length()-8);
		map.put("telephone", telephone);
		map.put("identity", 2);
		try {
			if(u.getId()!=null){
				int nus= userMapper.updateByPrimaryKeySelective(u);
			}else{
				List<User> list=userMapper.getLogin(map);
				if(list.size()>0){
					return new ReturnData(202,"This number is already registered. Please enter a different number.");
				}
				//first Name 的前4个 last的首个字符  然后加上编号
				String firstName=u.getFirstName();
				String result=firstName;
				if(!StringTools.isEmpty(firstName)&&firstName.length()>5){
					result=firstName.substring(0, 4).toUpperCase();
				}
				String last=u.getName();
				System.out.println(result);
				if(!StringTools.isEmpty(last)&&last.length()>1){
					System.out.println(last.substring(0, 1).toUpperCase());
					result+=last.substring(0, 1).toUpperCase();
				}
				String inviattionCode = result.toUpperCase();
				Integer counts=userMapper.queryInviattionCode(inviattionCode);// inviattionCode是否已被使用
				if (RegexUtil.isNull(counts)) {
					u.setInviattionCode(inviattionCode+"1");
				} else {
					u.setInviattionCode(inviattionCode+(counts+1));
				}
				u.setIdentity(2);
				u.setCreateTime(new Date());
				u.setUseEquipment("driver"+new Date().getTime());
				u.setPicture(getFileUrl(u.getPicture(),request));//头像
				u.setIsOnline(2);//是否在线  是否在线  1在线 2离线
				int num = userMapper.insertSelective(u);
				if(num==0){
					return new ReturnData(206,"Save Fail");
				}
				List<User>  list2=userMapper.getLogin(map);
				RongCloud rongCloud = RongCloud.getInstance(Constant.RONG_CLOUD_appKey, Constant.RONG_CLOUD_appSecret);
				 if(list2.size()>0){
					 TokenResult userGetTokenResult = rongCloud.user.getToken(list2.get(0).getId().toString(), list2.get(0).getFirstName(), "http://13.55.2.125:8080//file//fab//user.jpg");
					 if(userGetTokenResult!=null&&userGetTokenResult.getCode()==200){
						 User uus = list2.get(0);
						 uus.setRongCloudToken(userGetTokenResult.getToken());//保存融云的token
						int nus= userMapper.updateByPrimaryKeySelective(uus);
						if(nus==0){
							return new ReturnData(208,"rongcloud registered");
						}
					 }else{
						 return new ReturnData(209,"Fail to registered rongcloud");
					 }
				 }
			}
			return new ReturnData(200,"保存成功");
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500,"Wow, that's wrong");
		}
	}
	 //将base64图片 写入文件
		public String getFileUrl(String file,HttpServletRequest request){
			 String  dir= "fab";     
			 String acesP ="";
			  String path = "";
			if(!"".equals(file)&&file!=null){
				 String content = file.split(";base64,")[1];
				 String jp = file.split(";base64,")[0].split("/")[1];
					// 写入磁盘
					BASE64Decoder decoder = new BASE64Decoder();
					try {
						byte[] decodedBytes = decoder.decodeBuffer(content);
						String trueFileName= UUIDUtil.getOrderSnByTime18()+"."+jp;
						 acesP = "http://"+ Constant.SERVER_NAME+":"+request.getServerPort()+"//"+"file"+"//"+dir+"//"+trueFileName;  
						 // 项目在容器中实际发布运行的根路径
				            String realPath =  request.getSession().getServletContext().getRealPath("/");
				            String path2 = realPath.substring(0,realPath.lastIndexOf(System.getProperty("file.separator")));
				            String p = realPath.substring(0, (path2.lastIndexOf(System.getProperty("file.separator"))))+System.getProperty("file.separator")+"file"+System.getProperty("file.separator")+dir;
				            // 设置存放图片文件的路径
				            path=p+System.getProperty("file.separator")+trueFileName;  
				            File localFile = new File(p+System.getProperty("file.separator"));
				            if(!localFile.exists()){
	                            localFile.mkdirs();
	                        }
						 FileOutputStream out = new FileOutputStream(path);
						out.write(decodedBytes);
						out.close();
					} catch (Exception e) {
						e.printStackTrace();
					}
			}
			return acesP;
		}

		@Override
		public void exportDriverList(String telephone,String createTime,String loginTime, Page page, HttpServletResponse response) {
			User user = new User();
			if(!StringTools.isEmpty(createTime)){
				user.setCreateTime(DateUtil.parseDate(createTime));
			}
			if(!StringTools.isEmpty(loginTime)){
				user.setLoginTime(DateUtil.parseDate(loginTime));
			}
			
			 List<Map> list = userMapper.getDrivers(user);
			 List<Object> list1 = new ArrayList<>();
			 for(Map u:list){
				 DriverListExport dle = new DriverListExport();
				 dle.setAddress((String)u.get("address"));
				 dle.setCarCount(String.valueOf((Long)u.get("carCount")));
				 
				 dle.setMileage((Double)u.get("mileage"));
				 dle.setName((String)u.get("firstName"));
				 String sexs = "male";
				 if(u.get("sex")!=null&&(int)u.get("sex")==1){
					 sexs = "female";
				 }else if(u.get("sex")!=null&&(int)u.get("sex")==2){
					 sexs = "other";
				 }
				 dle.setSex(sexs);
				 dle.setTelephone((String)u.get("telephone"));
				 dle.setRemark((Double)u.get("remark"));
				 dle.setLicensePlate((String)u.get("licensePlate"));
				 dle.setCreateTime(DateUtil.format((Date)u.get("create_time"), "yyyy-MM-dd"));
				 list1.add(dle);
			 }
			 String[] Title = {"Drivers Name","Drivers Number", "Drivers gender",  "Drivers address",  "Numbers of vehicle","License Plate Number", "Kilometres", "Drivers review rating","Registration time"};
		    ExportExcel.exportExcel("Drivers_list.xls", Title, list1, response);
			
		}

		//模板弹框
		@Override
		public Object getList(String telephone, Integer pageNo, Integer pageSize,Integer identity) {
			  Map<String,Object> map = new HashMap<>();
			  if(!StringTools.isEmpty(telephone)){
			    	map.put("telephone", telephone);
			    }
			  if(!RegexUtil.isNull(identity)){
				  if(identity==3){
					  identity=null;
				  }
				  map.put("identity", identity);
			  }
			 try {
				    PageHelper.startPage(pageNo,pageSize);
					List<User> list = userMapper.getNameAndTel(map);
					PageInfo<User> info = new PageInfo(list);
					Integer totalPage= info.getPages();
					Integer totalRecord = (int) info.getTotal();
					return new ReturnData(list,totalPage,totalRecord,200,"User list ");
			} catch (Exception e) {
				e.printStackTrace();
				return new ReturnData(500,"Wow, that's wrong");
			}
		}

		@Override
		public Object getUserCouponList(String couponNo, Integer pageNo, Integer pageSize, String couponCode,
				String couponName, String userName,String startTime,String endTime,String giftedPeopleName) {
			Map<String,Object> map = new HashMap<>();
			if(!StringTools.isEmpty(couponNo)){
				map.put("couponNo", couponNo);
			}
			if(!StringTools.isEmpty(couponCode)){
				map.put("couponCode", couponCode);
			}
			if(!StringTools.isEmpty(couponName)){
				map.put("couponName", couponName);
			}
			if(!StringTools.isEmpty(userName)){
				map.put("userName", userName);
			}
			if(!StringTools.isEmpty(startTime)&&!StringTools.isEmpty(endTime)){
				 String[] startTime1= startTime.split("/");
			    	String[] endTime1= endTime.split("/");
			    	map.put("startTime", startTime1[2]+"-"+startTime1[1]+"-"+startTime1[0]);
			    	map.put("endTime", endTime1[2]+"-"+endTime1[1]+"-"+endTime1[0]);
				
			}
			if(!StringTools.isEmpty(giftedPeopleName)){
				map.put("giftedPeopleName", giftedPeopleName);
			}
			try {
				PageHelper.startPage(pageNo, pageSize);
				 List<UserCoupon> list=	userCouponMapper.getWebsiteCorporateCouponsList(map);
				 PageInfo<UserCoupon> info = new PageInfo<>(list);
				 return new ReturnData(list,info.getPages(),(int)info.getTotal(),200,"success");
			} catch (Exception e) {
				e.printStackTrace();
				return new ReturnData(500,"Wow, that's wrong");
			}
			
		}

		//司机接单里程列表
		@Override
		public Object getReceiveMileage(String startTime, String endTime, String licensePlate,Integer carType,String telephone, Integer pageNo,
				Integer pageSize) {
			  Map<String,Object> map = new HashMap<>();
			if(!StringTools.isEmpty(startTime)&&!StringTools.isEmpty(endTime)){
				 String[] startTime1= startTime.split("/");
			    	String[] endTime1= endTime.split("/");
			    	map.put("startTime", startTime1[2]+"-"+startTime1[1]+"-"+startTime1[0]);
			    	map.put("endTime", endTime1[2]+"-"+endTime1[1]+"-"+endTime1[0]);
		    }
		    if(!StringTools.isEmpty(licensePlate)){
		    	map.put("licensePlate", licensePlate);
		    }
		    if(!RegexUtil.isNull(carType)){
		    	map.put("carType", carType);
		    }
		    if(!StringTools.isEmpty(telephone)){
		    		if(telephone.length()>8){
			    		telephone=telephone.substring(telephone.length()-8);
			    	}
			    	map.put("telephone", telephone);
		    }
		    try {
		    	map.put("identity", 2);
		    	PageHelper.startPage(pageNo,pageSize);
				List<Map> list = userMapper.mileageStatistics(map);
				PageInfo<User> info = new PageInfo(list);
				Integer totalPage= info.getPages();
				Integer totalRecord = (int) info.getTotal();
				return new ReturnData(list,totalPage,totalRecord,200,"User list ");
			} catch (Exception e) {
				e.printStackTrace();
				return new ReturnData(500,"Wow, that's wrong");
			}
		}

		@Override
		public Object giftGivingRecords(String json) {
			User u= StringTools.json2Obj(json, User.class);
			if(u==null){
				return new ReturnData(202,"The parameter list cannot be empty！");
			}
			try {
				User uu=userMapper.selectByPrimaryKey(u.getId());
				String giving_feedback =uu.getGiving_feedback()==null?"":uu.getGiving_feedback();
				giving_feedback+=u.getGiving_feedback()+";";
				uu.setGiving_feedback(giving_feedback);;
				int n=userMapper.updateByPrimaryKeySelective(uu);
				if(n==0){
					return new ReturnData(202,"fail");
				}
				return new ReturnData(200,"successful");
			} catch (Exception e) {
				e.printStackTrace();
				return new ReturnData(500,"Wow, that's wrong");
			}
		}

		@Override
		public Object deleteUser(Long id) {
			try {
				int num=userMapper.deleteByPrimaryKey(id);
				if(num==0){
					return new ReturnData(202,"fail");
				}
				Map<String,Object> map =new HashMap();
				Long[] l={id};
				map.put("driverIds", l);
				 List<GisRecord> li=gisRecordMapper.selectByDriverId(map);
				 for(GisRecord gr:li){//删除司机之后
					 gisRecordMapper.deleteByPrimaryKey(gr.getId());
				 }
				return new ReturnData(200,"successful");
			} catch (Exception e) {
				e.printStackTrace();
				return new ReturnData(500,"Wow, that's wrong");
			}
		}

		@Override
		public Object addUser(String json,HttpServletRequest request) {
			User u = StringTools.json2Obj(json, User.class);
			if (u == null) {
				return new ReturnData(208, "List must be filled！");
			}
			Map<String, Object> map = new HashMap<>();
			map.put("telephone", u.getTelephone());
			map.put("identity", 1);// 用户端
			map.put("isDeleted", 0);// 判断该用户 没有被删除 是否删除 0否 1是
			List<User> list1 = userMapper.getLogin(map);// 查询电话是否已被使用
			if (list1.size() > 0) {
				// 判断这个账号是否已经被删除 没有被删除 则不能注册
				return new ReturnData(204, "The number you’ve entered is in use!");
			} else {// 作为新用户
				u.setIdentity(1);
				u.setCreateTime(new Date());
				String password = u.getPassword();
				if (!StringTools.isEmpty(password) && password.length() < 6 && password.length() > 18) {
					return new ReturnData(207,"Use between 8 – 19 characters in length!");
				}
				String newPass;
				try {
					newPass = MD5Util.getMD5(password);
					u.setPassword(newPass);
				} catch (NoSuchAlgorithmException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (NullPointerException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				String picture="";
				if(StringTools.isEmpty(u.getPicture())){
					picture="http://"+Constant.SERVER_NAME+"//file//fab//user.jpg";
				}else{
					 picture=getFileUrl(u.getPicture(),request);
					
				}
				u.setPicture(picture);//头像
				int num = userMapper.insertSelective(u);
				if(num==0){
					return new ReturnData(206,"Save Fail");
				}
				map.put("identity", 1);
				map.put("telephone", u.getTelephone());
				List<User>  list2=userMapper.getLogin(map);
				RongCloud rongCloud = RongCloud.getInstance(Constant.RONG_CLOUD_appKey, Constant.RONG_CLOUD_appSecret);
				 if(list2.size()>0){
					 TokenResult userGetTokenResult;
					try {
						userGetTokenResult = rongCloud.user.getToken(list2.get(0).getId().toString(), list2.get(0).getFirstName(), picture);
						if(userGetTokenResult!=null&&userGetTokenResult.getCode()==200){
							 User uus = list2.get(0);
							 uus.setRongCloudToken(userGetTokenResult.getToken());//保存融云的token
							int nus= userMapper.updateByPrimaryKeySelective(uus);
							if(nus==0){
								return new ReturnData(208,"rongcloud registered");
							}
							u.getUc().setCreateTime(new Date());
							userCouponMapper.insertSelective(u.getUc());
						 }else{
							 return new ReturnData(209,"Fail to registered rongcloud");
						 }
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						return new ReturnData(500,"Wow, that's wrong");
					}
				 }
				 return new ReturnData(200,"success");
			}
		}
   
		//发送短信
		@Override
		public ReturnData sendSMS(String json) {
			Authcode ac = StringTools.json2Obj(json, Authcode.class);
			if(ac==null){
				return new ReturnData(208, "List must be filled！");
			}
			Map<String, Object> params = new HashMap<>();
			params.put("username", "fabtech");// 发送短信与登录后台的用户名
			params.put("password", "fabtech2017");// 登录密码
			String phone=ac.getPhone();
			phone=phone.substring(phone.length()-8);
			// String s =telephone.substring(0, 1);
			/*
			 * if("0".equals(s)){ telephone =telephone.substring(1,
			 * telephone.length()); }
			 */
			params.put("to", "614" + phone); // 0400111222,0400222333
			params.put("from", "fab");// 发送者
			params.put("message", ac.getVcode());
			params.put("delay", "0");// 延迟时间
				
				try {
					// 发送消息返回的内容
					String result = HttpRequestUtil.sendRequestByPost("https://api.smsbroadcast.com.au/api-adv.php", params);
					/**
					 * OK : 61400111222:2942263 --------- --- OK : This message was
					 * accepted BAD:0400abc111 :Invalid Number ----------BAD: This
					 * message was invalid. (eg, invalid phone number) ERROR: Username
					 * or password is incorrect. --ERROR: The request failed. (eg, wrong
					 * username/password or missing a required parameter )
					 */
					// 字符串中包含OK
					/* if(result.indexOf("OK")!=-1){ } */
					if (result.indexOf("BAD") != -1) {// 号码无效 发送不成功
						String[] strlist = result.split(":");
						String errorMessage = strlist[2];// 错误提示消息
						return new ReturnData(201, errorMessage);
					} else if (result.indexOf("ERROR") != -1) {// 错误
						String[] strlist = result.split(":");
						String errorMessage = strlist[1];// 错误消息
						return new ReturnData(201, errorMessage);
					}else {
						ac.setCreateDate(new Date());
						ac.setPlatform(8);
						int code = authCodeMapper.insertSelective(ac);// 保存验证码发送时间 与记录
						if(code==0){
							return new ReturnData(209,"Failed to send message");
						}
						return new ReturnData(200, "success");
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					return new ReturnData(500, "Wow, that's wrong ");
				}
		}
   
		//直接给乘客赠送优惠劵
		@Override
		public ReturnData sendACoupon(String json) {
			UserCoupon uc =StringTools.json2Obj(json, UserCoupon.class);
			if(uc==null){
				return new ReturnData(201,"List must be filled！");
			}
			try {
				uc.setCouponOffsetMoney(uc.getCouponMoney());
				uc.setCreateTime(new Date());
				String no=userCouponMapper.getMaxNo();
				if(StringTools.isEmpty(no)){
					no="SYS00001";
				}else{
					Integer no1 =Integer.parseInt(no)+1;
					if(no1<10){
						no = "SYS0000"+no1;
					}else if(no1>=10&no1<100){
						no = "SYS000"+no1;
					}else if(no1>=100&no1<1000){
						no = "SYS00"+no1;
					}else if(no1>=1000&no1<10000){
						no = "SYS0"+no1;
					}else{
						no = "SYS"+no1;
					}
				}
				uc.setCouponNo(no);
				uc.setCouponCode(RandomUtil.getRandomNumberNozeroStart(11));
				int num=userCouponMapper.insertSelective(uc);
				if(num==0){
					return new ReturnData(202,"fail");
				}
				return new ReturnData(200,"success");
			} catch (Exception e) {
				e.printStackTrace();
				return new ReturnData(500, "Wow, that's wrong ");
			}
		}

		
	

}
